 //
//  PhotoBaseManager.m
//  Filmax Pictures
//
//  Created by Jonas on 16/8/19.
//  Copyright © 2016年 Jonas. All rights reserved.
//

#import "PhotoBaseManager.h" 
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

static PhotoBaseManager * phtoGraph;
@implementation PhotoBaseManager

+ (PhotoBaseManager *)photoBaseShareManage{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        phtoGraph = [[PhotoBaseManager alloc] init];
    });
    
    return phtoGraph;
}

#pragma mark - 图片浏览和删除功能
//图片浏览
- (void)tapBrowser:(NSInteger)selectIndext imageMutableArray:(NSMutableArray *)imageMutableArray viewController:(UIViewController * )viewController{
    
    //图片浏览器
    ZLPhotoPickerBrowserViewController *pickerBrowser = [[ZLPhotoPickerBrowserViewController alloc]init];
    //淡入淡出效果
    pickerBrowser.status = UIViewAnimationAnimationStatusFade;
    //是否可以有删除功能
    pickerBrowser.editing = YES;
    
    pickerBrowser.delegate = self;
    
    //现有图片加入数组
    NSMutableArray *mutableArryI = [NSMutableArray array];
    
    for (int i = 0;i < imageMutableArray.count ; i++) {
        
        ZLPhotoPickerBrowserPhoto *photo = [[ZLPhotoPickerBrowserPhoto alloc]init];
        if (imageMutableArray[i] == nil) {
            photo.thumbImage = [UIImage imageNamed:@"u68"];
            photo.thumbImage = [UIImage imageNamed:@"u68"];
        } else {
            photo.thumbImage = imageMutableArray[i]; //[UIImage imageWithData:imageMutableArray[i]];
            photo.photoImage = imageMutableArray[i];//[UIImage imageWithData:imageMutableArray[i]];
        }
        
        [mutableArryI addObject:photo];
    }
    
//    NSLog(@" 选择的第几个 %ld 存放照片的数组 %@",(long)selectIndext,[[DataBaseManager shareManager] getImageFromDocuments:imageMutableArray[0]]);
    
    pickerBrowser.photos = mutableArryI;
    //当前选中值
    pickerBrowser.currentIndex = selectIndext;
    //展开控制器
    [pickerBrowser showPickerVc:viewController];
}

//删除照片
- (void)photoBrowser:(ZLPhotoPickerBrowserViewController *)photoBrowser removePhotoAtIndex:(NSInteger)index{
    _deletPicture(index);
}

#pragma mark - 相机获取图片并图片保存
- (void)getPhotoPicture:(UIViewController *)viewController type:(NSInteger)fromType {
    //是相机----
    if (fromType == 0) {
        if([PhotoBaseManager judgeTheRootOpenCamera]){
            UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init];
            imagePickController.delegate = self;
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                return;
            }
            imagePickController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            [viewController presentViewController:imagePickController animated:YES completion:nil];
        } else {
            [PhotoBaseManager enterTheCameraFunction:viewController];
        }
    }
    
    //1是图片
    if (fromType == 1) {
        //点击后进行的操作----跳转到相册界面
        UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
        // 设置资源类型
        pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        // 设置代理, 通过代理方法获取选择的图片
        pickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        pickerController.delegate = self;
        [viewController presentViewController:pickerController animated:YES completion:nil];
    }
}


//拍摄照片
- (void)getPhotoPicture:(UIViewController *)viewController {
    if([PhotoBaseManager judgeTheRootOpenCamera]){
        
        UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init];
        imagePickController.delegate = self;
        imagePickController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [viewController presentViewController:imagePickController animated:YES completion:nil];
    } else {
        [PhotoBaseManager enterTheCameraFunction:viewController];
    } 
}

//相机获取数据
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *imageNeed= [self imageCompressForWidth:[info objectForKey:@"UIImagePickerControllerOriginalImage"] targetWidth:500];
    //UIImage *imageNeed = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
//    NSData * imageData = UIImageJPEGRepresentation(imageNeed, 1.0);
    NSData * imageData = [self compressImage:imageNeed toMaxFileSize:50];
    
    if (self.getPhotoImage) {
        self.getPhotoImage(imageData);
    }
}

//图片压缩大小
- (NSData *)compressImage:(UIImage *)image toMaxFileSize:(NSInteger)maxFileSize {
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length]/1024 > maxFileSize && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    NSLog(@"%lu",imageData.length/1024);
    return imageData;
//    UIImage *compressedImage = [UIImage imageWithData:imageData];
//    return compressedImage;
}

#pragma mark - 判断是否开启拍照权限问题
//没有权限时跳入照片服务开启功能
+ (void)openCameraFunction{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=CAMERA"]];
    
}
//判断是否有权利进行拍照
+ (BOOL)judgeTheRootOpenCamera{
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
        //无权限
        return NO;
    }
    return YES;
}

//提示拍照权限
+ (void)enterTheCameraFunction:(UIViewController *)viewController{
    
    UIAlertController * alterController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先打开拍照权限设置 -> 隐私 -> 相机 -> app" preferredStyle:UIAlertControllerStyleAlert];
    
    __weak __typeof(self) weakSelf = self;
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf openCameraFunction];
    }];
    
    [alterController addAction:action];
    [viewController presentViewController:alterController animated:YES completion:nil];
}

//图片压缩宽度
- (UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if(CGSizeEqualToSize(imageSize, size) == NO){
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if(widthFactor > heightFactor){
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(size);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    
    UIGraphicsEndImageContext();
    return newImage;
}

@end
